package com.forlove.app.qselect.answer.ui;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.forlove.app.R;
import com.forlove.app.common.base.event.BaseMessageEvent;
import com.forlove.app.common.base.ui.BaseActivity;
import com.forlove.app.common.utils.AppPreferenceHelper;
import com.forlove.app.common.utils.MyTimeUtils;
import com.forlove.app.common.widget.GuideWindow;
import com.forlove.app.event.ActiveFlagEvent;
import com.forlove.app.manager.EventManager;
import com.forlove.app.manager.UserManager;
import com.forlove.app.qselect.MainActivity;
import com.forlove.app.qselect.answer.entity.AnswerEntity;
import com.forlove.app.qselect.answer.presenter.LimitAnswerPresenter;
import com.forlove.app.qselect.answer.view.LimitAnswerView;
import com.forlove.app.qselect.friend.ui.InviteContactsActivity;
import com.forlove.app.qselect.index.ui.IndexFragment;
import com.forlove.app.qselect.login.entity.UserEntity;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by yjl on 2017/10/12.
 */

public class LimitAnswerActivity extends BaseActivity<LimitAnswerPresenter>
        implements View.OnClickListener, LimitAnswerView {

    public static String KEY_EXPIRE_TIME = "expire_time";//锁题时间
    public static String KEY_CIRCLE_NUM = "circle_num";//被圈次数
    public static String KEY_ANSWER_BATCH = "answer_batch";//答题批次
    public static String KEY_UNLOCK_NUM = "unlock_num";//解锁答题宝石数
    @BindView(R.id.bt_invite_friend)
    TextView bt_invite_friend;

    @BindView(R.id.limit_home)
    FrameLayout limit_home;

    @BindView(R.id.image_home)
    ImageView image_home;// 返回home页

    @BindView(R.id.text_hot_num)
    TextView text_hot_num;  //被圈选数

    @BindView(R.id.text_limit_time)
    TextView text_limit_time; //答题限制时间

    @BindView(R.id.image_question)
    ImageView image_question;

    @BindView(R.id.text_limit_tip)
    TextView text_limit_tip;

    @BindView(R.id.text_tip)
    TextView text_tip;

    //    @BindView(R.id.text_invite_tip)
//    TextView text_invite_tip;
    @BindView(R.id.bt_unlock_answer)
    FrameLayout bt_unlock_answer;

    @BindView(R.id.text_unlock_answer)
    TextView text_unlock_answer;

    @BindView(R.id.view_unread_num)
    TextView view_unread_num;

    private long limitTime = 0;
    private int circleNum = 0;
    private int batch = 0;
    private int unlockcost = -1;//解锁答题使用宝石数
    private Handler handler;
    private boolean showTip = false;

    @Override
    public int getLayoutId() {
        return R.layout.activity_limit_circle;
    }

    @Override
    public void initView() {
        if (presenter == null) {
            presenter = new LimitAnswerPresenter(this);
        }
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            limitTime = bundle.getLong(KEY_EXPIRE_TIME, 0);
            circleNum = bundle.getInt(KEY_CIRCLE_NUM, 0);
            batch = bundle.getInt(KEY_ANSWER_BATCH, 0);
            unlockcost = bundle.getInt(KEY_UNLOCK_NUM, -1);
        }
        showTip = getShowTip();
        initHandler();
        bt_invite_friend.setOnClickListener(this);
        limit_home.setOnClickListener(this);
        if (unlockcost > 0) {
            text_unlock_answer.setText(String.format(getString(R.string.str_unlock_answer), unlockcost));
            bt_unlock_answer.setVisibility(View.VISIBLE);
        } else {
            bt_unlock_answer.setVisibility(View.GONE);
        }
        if (limitTime > 0) {
            text_limit_time.setText(MyTimeUtils.getShiFenMiao(limitTime));
            text_hot_num.setText(circleNum + "");
            handler.sendEmptyMessage(88888);
        } else if (limitTime < 0) {
            image_question.setBackgroundResource(R.mipmap.image_answer_over);
            text_limit_tip.setText("今日圈一圈已达上限，明日继续");
            text_limit_tip.setTextColor(Color.parseColor("#333333"));
            text_limit_tip.setTextSize(16);
            text_limit_time.setVisibility(View.INVISIBLE);
            text_tip.setVisibility(View.INVISIBLE);
            //答题上限不显示宝石解锁
            bt_unlock_answer.setVisibility(View.INVISIBLE);
        }
        if (batch == 1) {
            bt_unlock_answer.setVisibility(View.GONE);
            bt_invite_friend.setVisibility(View.GONE);
        }

        int num = MainActivity.unread_num + MainActivity.undealwith_request;
        if (num > 0) {
            showUnreadNum(num);
        } else {
            hideUnreadNum();
        }
    }

    private void showUnreadNum(int unread) {
        view_unread_num.setVisibility(View.VISIBLE);
        if (unread > 99) {
            view_unread_num.setText(99 + "+");
        } else {
            view_unread_num.setText(unread + "");
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        // TODO Auto-generated method stub
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus && showTip) {
            showTip = false;
            showGuideView(image_home);
            saveShowTip(false);
        }
    }

    private void initHandler() {
        if (handler == null) {
            handler = new Handler(getMainLooper()) {
                @Override
                public void handleMessage(Message msg) {
                    if (msg.what == 88888) {
                        limitTime--;
                        text_limit_time.setText(MyTimeUtils.getShiFenMiao(limitTime));
                        if (limitTime == 0) {
                            if (isShowing()) {
                                startActivity(new Intent(LimitAnswerActivity.this, AnswerSubjectActivity.class));
                            }
                            finish();
                        }
                        if (limitTime > 0) {
                            Message message = new Message();
                            message.what = 88888;
                            message.replyTo = new Messenger(mHandler);
                            if (handler != null) {
                                handler.sendMessageDelayed(message, 1000);
                            }
                        }
                    }
                }
            };
        }

    }

    private void showGuideView(View mainView) {
        boolean ishow = true;
        if (ishow) {
            ImageView imageView = new ImageView(this);
            imageView.setBackgroundResource(R.mipmap.image_limit_answer_tip);
            imageView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT));
            GuideWindow.Builder builder = new GuideWindow.Builder(this);
            builder.setContentView(imageView);
            builder.showAsDropDown(mainView);
        }
    }

    private void hideUnreadNum() {
        view_unread_num.setVisibility(View.INVISIBLE);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_invite_friend:
                Intent intent = new Intent(this, InviteContactsActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("from", "LimitAnswerActivity");
                intent.putExtras(bundle);
                startActivity(intent);
                finish();
                break;
            case R.id.limit_home:
                toMainActivity(MainActivity.POSITION_INDEX, IndexFragment.POSITION_INDEX_MiNE);
                this.finish();
                break;
        }
    }

    @OnClick(R.id.bt_unlock_answer)
    public void clickDiamondUnlock() {
        if (circleNum > 0) {
            presenter.loadResetQuestionData(true);
        } else {
            Toast.makeText(this, "宝石数量不足!", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
    }

    @Override
    protected void onDestroy() {
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
        super.onDestroy();
    }

    private void saveShowTip(boolean isShow) {
        AppPreferenceHelper.getInstance(this).putBoolean("limit_show_tip", isShow);
    }

    private boolean getShowTip() {
        return AppPreferenceHelper.getInstance(this).getBoolean("limit_show_tip", true);
    }

    @Override
    public void onEventMainThread(BaseMessageEvent event) {
        if (event != null && event.eventId == EventManager.EVENT_NEW_FLAG) {
            if (event instanceof ActiveFlagEvent) {
                ActiveFlagEvent activeFlagEvent = (ActiveFlagEvent) event;
                int num = activeFlagEvent.unread + activeFlagEvent.requestCount;
                if (num > 0) {
                    showUnreadNum(num);
                } else {
                    hideUnreadNum();
                }
            }
        } else if (event != null
                && event.eventId == EventManager.EVENT_UPDATE_USERINFO) {
            UserEntity userEntity = UserManager.getUesrInfo(this);
            if (userEntity != null) {
                text_hot_num.setText(userEntity.diamond + "");
            }
        }
    }

    @Override
    public void showResetAnswerView(AnswerEntity answerEntity) {
        Toast.makeText(this, "解锁成功！", Toast.LENGTH_SHORT).show();
        UserEntity userEntity = UserManager.getUesrInfo(this);
        if (circleNum > unlockcost) {
            text_hot_num.setText((circleNum - unlockcost) + "");
            userEntity.diamond = circleNum - unlockcost;
        } else {
            text_hot_num.setText(0 + "");
            userEntity.diamond = 0;
        }
        UserManager.saveUserInfo(this, userEntity);

        Intent intent = new Intent(this, AnswerSubjectActivity.class);
        Bundle bundle = new Bundle();
        if (answerEntity != null) {
            bundle.putSerializable("answer", answerEntity.serializeToString());
        }
        intent.putExtras(bundle);
        startActivity(intent);
        this.finish();
    }
}
